Python: Conditional Average Treatment Effects (CATEs)#

In this simple example, we illustrate how the DoubleML package can be used to estimate conditional average treatment effects with B-splines for one or two-dimensional effects.

Data#

We define a data generating process to create synthetic data to compare the estimates to the true effect. The data generating process is based on the Monte Carlo simulation from this paper and this implementation from EconML.

[1]:
import numpy as np
import pandas as pd
import doubleml as dml

The data is generated as

$ \begin{align} Y_i & = g(X_i)T_i + \langle W_i,\gamma_0\rangle + \epsilon_i \\ T_i & = \langle W_i,\beta_0\rangle +\eta_i, \end{align} $

where \(W_i\sim\mathcal{N}(0,I_{d_w})\), \(X_i\sim\mathcal{U}[0,1]^{d_x}\) and \(\epsilon_i,\eta_i\sim\mathcal{U}[0,1]\). The coefficient vectors \(\gamma_0\) and \(\beta_0\) both have small random support which values are drawn independently from \(\mathcal{U}[0,1]\). Further, \(g(x)\) defines the conditional treatment effect, which is defined differently depending on the dimension of \(x\).

If \(x\) is univariate the conditional treatment effect takes the following form

\[g(x) = \exp(2x) + 3\sin(4x),\]

whereas for a two-dimensional variable \(x=(x_1,x_2)\) the conditional treatment effect is defined as

\[g(x) = \exp(2x_1) + 3\sin(4x_2).\]
[2]:
def treatment_effect_1d(x):
    te = np.exp(2 * x) + 3 * np.sin(4 * x)
    return te

def treatment_effect_2d(x):
    te = np.exp(2 * x[0]) + 3 * np.sin(4 * x[1])
    return te

def create_synthetic_data(n_samples=200, n_w=30, support_size=5, n_x=1):
    """
    Creates a simple synthetic example for conditional treatment effects.

    Parameters
    ----------
    n_samples : int
        Number of samples.
        Default is ``200``.

    n_w : int
        Dimension of covariates.
        Default is ``30``.

    support_size : int
        Number of relevant covariates.
        Default is ``5``.

    n_x : int
        Dimension of treatment variable.
        Default is ``1``.

    Returns
    -------
     data : pd.DataFrame
            A data frame.

    """
    # Outcome support
    # With the next two lines we are effectively choosing the matrix gamma in the example
    support_y = np.random.choice(np.arange(n_w), size=support_size, replace=False)
    coefs_y = np.random.uniform(0, 1, size=support_size)
    # Define the function to generate the noise
    epsilon_sample = lambda n: np.random.uniform(-1, 1, size=n_samples)
    # Treatment support
    # Assuming the matrices gamma and beta have the same non-zero components
    support_t = support_y
    coefs_t = np.random.uniform(0, 1, size=support_size)
    # Define the function to generate the noise
    eta_sample = lambda n: np.random.uniform(-1, 1, size=n_samples)

    # Generate controls, covariates, treatments and outcomes
    w = np.random.normal(0, 1, size=(n_samples, n_w))
    x = np.random.uniform(0, 1, size=(n_samples, n_x))
    # Heterogeneous treatment effects
    if n_x == 1:
        te = np.array([treatment_effect_1d(x_i) for x_i in x]).reshape(-1)
    elif n_x == 2:
        te = np.array([treatment_effect_2d(x_i) for x_i in x]).reshape(-1)
    # Define treatment
    log_odds = np.dot(w[:, support_t], coefs_t) + eta_sample(n_samples)
    t_sigmoid = 1 / (1 + np.exp(-log_odds))
    t = np.array([np.random.binomial(1, p) for p in t_sigmoid])
    # Define the outcome
    y = te * t + np.dot(w[:, support_y], coefs_y) + epsilon_sample(n_samples)

    # Now we build the dataset
    y_df = pd.DataFrame({'y': y})
    if n_x == 1:
        x_df = pd.DataFrame({'x': x.reshape(-1)})
    elif n_x == 2:
        x_df = pd.DataFrame({'x_0': x[:,0],
                             'x_1': x[:,1]})
    t_df = pd.DataFrame({'t': t})
    w_df = pd.DataFrame(data=w, index=np.arange(w.shape[0]), columns=[f'w_{i}' for i in range(w.shape[1])])

    data = pd.concat([y_df, x_df, t_df, w_df], axis=1)

    covariates = list(w_df.columns.values) + list(x_df.columns.values)
    return data, covariates, te

One-dimensional Example#

We start with \(X\) being one-dimensional and create our training data.

[3]:
# DGP constants
np.random.seed(42)
n_samples = 2000
n_w = 10
support_size = 5
n_x = 1

# Create data
data, covariates, true_effect = create_synthetic_data(n_samples=n_samples, n_w=n_w, support_size=support_size, n_x=n_x)
data_dml_base = dml.DoubleMLData(data,
                                 y_col='y',
                                 d_cols='t',
                                 x_cols=covariates)

Next, define the learners for the nuisance functions and fit the IRM Model. Remark that the learners are not optimal for the linear form of this example.

[4]:
# First stage estimation
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
randomForest_reg = RandomForestRegressor(n_estimators=500)
randomForest_class = RandomForestClassifier(n_estimators=500)

np.random.seed(42)

dml_irm = dml.DoubleMLIRM(data_dml_base,
                          ml_g=randomForest_reg,
                          ml_m=randomForest_class,
                          trimming_threshold=0.01,
                          n_folds=5)
print("Training IRM Model")
dml_irm.fit()
Training IRM Model
[4]:
<doubleml.double_ml_irm.DoubleMLIRM at 0x7f9918c5a820>

To estimate the CATE, we rely on the best-linear-predictor of the linear score as in Semenova et al. To approximate the target function \(g(x)\) with a linear form, we have to define a data frame of basis functions. Here, we rely on patsy to construct a suitable basis of B-splines.

[5]:
import patsy
design_matrix = patsy.dmatrix("bs(x, df=5, degree=2)", {"x":data["x"]})
spline_basis = pd.DataFrame(design_matrix)

To estimate the parameters to calculate the CATE estimate call the cate() method and supply the dataframe of basis elements.

[6]:
cate = dml_irm.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================

------------------ Fit summary ------------------
       coef   std err          t          P>|t|    [0.025    0.975]
0  0.800985  0.187226   4.278164   1.973568e-05  0.433805  1.168165
1  2.317576  0.312855   7.407836   1.885192e-13  1.704020  2.931132
2  4.731110  0.199998  23.655730  2.996077e-109  4.338882  5.123338
3  4.501506  0.239412  18.802350   9.746797e-73  4.031982  4.971030
4  3.865116  0.245950  15.715036   1.485625e-52  3.382770  4.347463
5  4.114845  0.266575  15.435994   7.270658e-51  3.592051  4.637639

To obtain the confidence intervals for the CATE, we have to call the confint() method and a supply a dataframe of basis elements. This could be the same basis as for fitting the CATE model or a new basis to e.g. evaluate the CATE model on a grid. Here, we will evaluate the CATE on a grid from 0.1 to 0.9 to plot the final results. Further, we construct uniform confidence intervals by setting the option joint and providing a number of bootstrap repetitions n_rep_boot.

[7]:
new_data = {"x": np.linspace(0.1, 0.9, 100)}
spline_grid = pd.DataFrame(patsy.build_design_matrices([design_matrix.design_info], new_data)[0])
df_cate = cate.confint(spline_grid, level=0.95, joint=True, n_rep_boot=2000)
print(df_cate)
       2.5 %    effect    97.5 %
0   2.161123  2.486602  2.812081
1   2.279878  2.607058  2.934238
2   2.394024  2.725133  3.056242
3   2.504552  2.840828  3.177103
4   2.612308  2.954141  3.295974
..       ...       ...       ...
95  4.480207  4.811954  5.143701
96  4.483368  4.809714  5.136060
97  4.487456  4.808597  5.129738
98  4.491828  4.808603  5.125377
99  4.495728  4.809731  5.123734

[100 rows x 3 columns]

Finally, we can plot our results and compare them with the true effect.

[8]:
from matplotlib import pyplot as plt
plt.rcParams['figure.figsize'] = 10., 7.5

df_cate['x'] = new_data['x']
df_cate['true_effect'] = treatment_effect_1d(new_data['x'])
fig, ax = plt.subplots()
ax.plot(df_cate['x'],df_cate['effect'], label='Estimated Effect')
ax.plot(df_cate['x'],df_cate['true_effect'], color="green", label='True Effect')
ax.fill_between(df_cate['x'], df_cate['2.5 %'], df_cate['97.5 %'], color='b', alpha=.3, label='Confidence Interval')

plt.legend()
plt.title('CATE')
plt.xlabel('x')
_ =  plt.ylabel('Effect and 95%-CI')
../_images/examples_py_double_ml_cate_16_0.png

Two-Dimensional Example#

It is also possible to estimate multi-dimensional conditional effects. We will use the same data-generating process as above, but let \(X\) be two-dimensional.

[9]:
# DGP constants
np.random.seed(42)
n_samples = 5000
n_w = 10
support_size = 5
n_x = 2
[10]:
# Create data
data, covariates, true_effect = create_synthetic_data(n_samples=n_samples, n_w=n_w, support_size=support_size, n_x=n_x)
data_dml_base = dml.DoubleMLData(data,
                                 y_col='y',
                                 d_cols='t',
                                 x_cols=covariates)

As univariate example estimate the IRM Model.

[11]:
# First stage estimation
from sklearn.ensemble import RandomForestClassifier, RandomForestRegressor
randomForest_reg = RandomForestRegressor(n_estimators=500)
randomForest_class = RandomForestClassifier(n_estimators=500)

np.random.seed(123)

dml_irm = dml.DoubleMLIRM(data_dml_base,
                          ml_g=randomForest_reg,
                          ml_m=randomForest_class,
                          trimming_threshold=0.01,
                          n_folds=5)
print("Training IRM Model")
dml_irm.fit()
Training IRM Model
[11]:
<doubleml.double_ml_irm.DoubleMLIRM at 0x7f9914008ac0>

As above, we will rely on the patsy package to construct the basis elements. In the two-dimensional case, we will construct a tensor product of B-splines (for more information see here).

[12]:
design_matrix = patsy.dmatrix("te(cr(x_0, df=6), cc(x_1, df=6)) - 1", {"x_0": data["x_0"], "x_1": data["x_1"]})
spline_basis = pd.DataFrame(design_matrix)

cate = dml_irm.cate(spline_basis)
print(cate)
================== DoubleMLBLP Object ==================

------------------ Fit summary ------------------
         coef   std err          t          P>|t|    [0.025     0.975]
0    0.604233  0.332103   1.819412   6.890880e-02 -0.046836   1.255302
1    3.125605  0.307803  10.154575   5.417216e-24  2.522176   3.729034
2    4.451022  0.324940  13.697978   5.996182e-42  3.813996   5.088048
3    4.213811  0.313247  13.452019   1.525932e-40  3.599707   4.827914
4    2.314430  0.318764   7.260634   4.450491e-13  1.689512   2.939349
5    0.699531  0.287962   2.429252   1.516527e-02  0.134999   1.264063
6    0.803563  0.170947   4.700667   2.663304e-06  0.468432   1.138694
7    3.463561  0.171227  20.227921   1.715967e-87  3.127881   3.799241
8    4.282365  0.168945  25.347725  2.107199e-133  3.951159   4.613572
9    3.966890  0.179375  22.115112  1.933984e-103  3.615236   4.318543
10   2.608630  0.171217  15.235777   2.910942e-51  2.272968   2.944292
11   0.844913  0.170626   4.951832   7.595500e-07  0.510410   1.179416
12   1.198591  0.174801   6.856877   7.898403e-12  0.855903   1.541279
13   4.461987  0.167341  26.663976  1.666402e-146  4.133924   4.790050
14   4.917113  0.163506  30.072978  1.124828e-182  4.596569   5.237657
15   4.952606  0.166034  29.828898  5.533714e-180  4.627106   5.278106
16   3.522473  0.166132  21.202881   1.389062e-95  3.196781   3.848165
17   1.394159  0.170747   8.165059   4.037491e-16  1.059420   1.728899
18   2.573164  0.169213  15.206629   4.455693e-51  2.241431   2.904896
19   5.395435  0.171672  31.428778  6.708865e-198  5.058882   5.731987
20   6.420662  0.173736  36.956496  2.478373e-264  6.080063   6.761260
21   6.133043  0.165315  37.099054  3.949421e-266  5.808952   6.457134
22   4.625297  0.165425  27.960039  6.916526e-160  4.300991   4.949604
23   2.348626  0.162656  14.439233   2.516821e-46  2.029748   2.667503
24   4.176464  0.163197  25.591588  8.597218e-136  3.856526   4.496402
25   7.024126  0.161962  43.369002   0.000000e+00  6.706609   7.341643
26   7.713400  0.171418  44.997519   0.000000e+00  7.377345   8.049456
27   7.544198  0.166797  45.229898   0.000000e+00  7.217203   7.871193
28   5.975691  0.175875  33.976913  1.070637e-227  5.630898   6.320483
29   4.329680  0.158862  27.254263  1.531250e-152  4.018240   4.641121
30   7.108494  0.351517  20.222310   1.906151e-87  6.419364   7.797623
31   9.673541  0.344538  28.076812  4.087311e-161  8.998093  10.348988
32  10.648766  0.359216  29.644502  5.842619e-178  9.944544  11.352987
33  10.022048  0.312943  32.025133  9.732374e-205  9.408541  10.635555
34   9.230270  0.307361  30.030686  3.300708e-182  8.627706   9.832834
35   6.120285  0.319289  19.168511   4.588444e-79  5.494339   6.746232

Finally, we create a new grid to evaluate and plot the effects.

[13]:
grid_size = 100
x_0 = np.linspace(0.1, 0.9, grid_size)
x_1 = np.linspace(0.1, 0.9, grid_size)
x_0, x_1 = np.meshgrid(x_0, x_1)

new_data = {"x_0": x_0.ravel(), "x_1": x_1.ravel()}
[14]:
spline_grid = pd.DataFrame(patsy.build_design_matrices([design_matrix.design_info], new_data)[0])
df_cate = cate.confint(spline_grid, joint=True, n_rep_boot=2000)
print(df_cate)
         2.5 %    effect    97.5 %
0     1.642251  2.103445  2.564639
1     1.657373  2.116454  2.575535
2     1.667890  2.130064  2.592238
3     1.675004  2.144320  2.613636
4     1.679988  2.159267  2.638546
...        ...       ...       ...
9995  4.180079  4.651675  5.123270
9996  4.261262  4.732416  5.203570
9997  4.337863  4.813105  5.288347
9998  4.409008  4.893745  5.378481
9999  4.474072  4.974339  5.474605

[10000 rows x 3 columns]
[15]:
import plotly.graph_objects as go

true_effect = np.array([treatment_effect_2d(x_i) for x_i in zip(x_0.ravel(), x_1.ravel())]).reshape(x_0.shape)
effect = np.asarray(df_cate['effect']).reshape(x_0.shape)
lower_bound = np.asarray(df_cate['2.5 %']).reshape(x_0.shape)
upper_bound = np.asarray(df_cate['97.5 %']).reshape(x_0.shape)

fig = go.Figure(data=[
    go.Surface(x=x_0,
               y=x_1,
               z=true_effect),
    go.Surface(x=x_0,
               y=x_1,
               z=upper_bound, showscale=False, opacity=0.4,colorscale='purp'),
    go.Surface(x=x_0,
               y=x_1,
               z=lower_bound, showscale=False, opacity=0.4,colorscale='purp'),
])
fig.update_traces(contours_z=dict(show=True, usecolormap=True,
                                  highlightcolor="limegreen", project_z=True))

fig.update_layout(scene = dict(
                    xaxis_title='X_0',
                    yaxis_title='X_1',
                    zaxis_title='Effect'),
                    width=700,
                    margin=dict(r=20, b=10, l=10, t=10))

fig.show()